#!/usr/bin/python
# coding=utf-8
import sqlite3
from flask import Flask, render_template, jsonify
import json
import random
app = Flask(__name__)
app.config.from_object('config')

login_name = None


# --------------------- html render ---------------------
@app.route('/')
def index():
    return render_template('brand_car_analysis.html')

@app.route('/brand_car_analysis')
def brand_car_analysis():
    return render_template('brand_car_analysis.html')

@app.route('/brand_car_score_analysis')
def brand_car_score_analysis():
    return render_template('brand_car_score_analysis.html')

@app.route('/car_price_analysis')
def car_price_analysis():
    return render_template('car_price_analysis.html')

# ------------------ ajax restful api -------------------



# 读取所有汽车数据
brand_info = {}
car_info = []
with open('all_car_info.txt',encoding='utf-8') as fout:
    for line in fout:
        car = json.loads(line.strip())
        brand = car['品牌']
        if brand not in brand_info:
            brand_info[brand] = [car]
        else:
            brand_info[brand].append(car)
        car_info.append(car)

print('汽车品牌：\n', '\t'.join(brand_info.keys()))

@app.route('/get_all_brands')
def get_all_brands():
    return jsonify(list(brand_info.keys()))

# 不同品牌汽车的数量
@app.route('/brand_car_count')
def brand_car_count():
    brands = list(brand_info.keys())
    # 为了显示好看，随机选取50个汽车品牌
    random.shuffle(brands)
    brands = brands[:50]
    counts = [len(brand_info[b]) for b in brands]

    results = list(zip(brands, counts))
    results = sorted(results, key=lambda k: k[1], reverse=True)
    zhibiao = [r[0] for r in results]
    counts = [r[1] for r in results]
    return jsonify({'keys': zhibiao, 'counts': counts})

# 不同类型汽车的数量分布
@app.route('/car_type_count/<props>')
def car_type_count(props):
    car_type_counts = {}
    for car in car_info:
        if props not in car:
            continue
        if car[props] not in car_type_counts:
            car_type_counts[car[props]] = 0
        car_type_counts[car[props]] += 1

    brands = list(car_type_counts.keys())
    counts = [car_type_counts[b] for b in brands]
    # return jsonify({'keys': brands, 'counts': counts})

    results = list(zip(brands, counts))
    results = sorted(results, key=lambda k: k[1], reverse=True)
    zhibiao = [r[0] for r in results if r[1] > 10]
    counts = [r[1] for r in results if r[1] > 10]
    return jsonify({'keys': zhibiao, 'counts': counts})

# 各汽车品牌的评分分布箱线图
@app.route('/brand_score/<props>/<brand>')
def brand_score(props, brand):
    cars = brand_info[brand]
    car_jibie_score = {}
    for car in cars:
        if car[props] not in car_jibie_score:
            car_jibie_score[car[props]] = []
        if car['评分'] != '暂无':
            car_jibie_score[car[props]].append(float(car['评分']))

    for jibie in list(car_jibie_score.keys()):
        if len(car_jibie_score[jibie]) == 0:
            del car_jibie_score[jibie]
            continue
        car_jibie_score[jibie] = sum(car_jibie_score[jibie]) / len(car_jibie_score[jibie]) if len(car_jibie_score[jibie]) > 0 else None

    jibie = list(car_jibie_score.keys())
    scores = [car_jibie_score[j] for j in jibie]
    results = list(zip(jibie, scores))
    results = sorted(results, key=lambda k: k[1], reverse=True)
    jibie = [r[0] for r in results if r[1]]
    scores = [r[1] for r in results if r[1]]
    return jsonify({'jibie': jibie, 'scores': scores, 'max_score': max(scores), 'min_score': min(scores)})


@app.route('/top20_score/<brand>')
def top20_score(brand):
    cars = brand_info[brand]
    car_scores = []
    for car in cars:
        if car['评分'] != '暂无':
            car_scores.append(car)
    results = sorted(car_scores, key=lambda car: car['评分'], reverse=True)
    
    if len(results) == 0:
        results = cars
    header = "<thead><tr>"
    print(results[0].keys())
    for col in results[0].keys():
        header += '<th>' + col + '</th>'
    header += '</tr></thead>'

    body = '<tbody>'
    for car in results:
        tds = ''.join(['<td>{}</td>'.format(v) for v in list(car.values())[:-1]])
        tds += '<td><a href="{}" target="_blank">查看</a></td>'.format(list(car.values())[-1])
        body += '<tr>' + tds + '</tr>'
    body += '</tbody>'
    html = header + body
    return html


@app.route('/get_brand_probs/<brand>')
def get_brand_probs(brand):
    """获取不同汽车品牌的汽车属性"""
    brand_cars = brand_info[brand]
    props = list(brand_cars[0].keys())

    props.remove('最低指导价')
    props.remove('最高指导价')
    props.remove('链接')

    ul = ''
    for i, prop in enumerate(props):
        if i == 0:
            ul += '<li class="active" id="first"><a id="{}" data-toggle="tab"><b>{}</b></a></li>'.format(prop, prop)
        else:
            ul += '<li><a id="{}" data-toggle="tab"><b>{}</b></a></li>'.format(prop, prop)
    return ul


@app.route('/brand_min_max_price/<props>/<brand>')
def brand_min_max_price(props, brand):
    """获取不同品牌汽车不同属性的最高价和最低价"""
    cars = brand_info[brand]
    car_min_price = {}
    car_max_price = {}
    for car in cars:
        if props not in car: continue

        if car[props] not in car_min_price:
            car_min_price[car[props]] = []
        if car['最低指导价'] != '':
            car_min_price[car[props]].append(float(car['最低指导价'][:-1]))

        if car[props] not in car_max_price:
            car_max_price[car[props]] = []
        if car['最高指导价'] != '':
            car_max_price[car[props]].append(float(car['最高指导价'][:-1]))

    for jibie in list(car_min_price.keys()):
        if len(car_min_price[jibie]) == 0:
            del car_min_price[jibie]
            continue
        car_min_price[jibie] = sum(car_min_price[jibie]) / len(car_min_price[jibie]) if len(car_min_price[jibie]) > 0 else None

    for jibie in list(car_max_price.keys()):
        if len(car_max_price[jibie]) == 0:
            del car_max_price[jibie]
            continue
        car_max_price[jibie] = sum(car_max_price[jibie]) / len(car_max_price[jibie]) if len(car_max_price[jibie]) > 0 else None

    props = list(car_min_price.keys())
    min_prices = [car_min_price[j] for j in props]
    max_prices = [car_max_price[j] for j in props]
    return jsonify({'props': props, 'min_prices': min_prices, 'max_prices':max_prices})


if __name__ == "__main__":
    app.run(host='127.0.0.1', port=5001)
